/**
 * 学生闯关留存数据
 */

import React from 'react';
import { connect } from 'react-redux';

import Tabs from 'material-ui/lib/tabs/tabs';
import Tab from 'material-ui/lib/tabs/tab';
import FlatButton from 'material-ui/lib/flat-button';
import TextField from 'material-ui/lib/TextField';

import { StudentFilter } from '../../components/smart/filter';
import ChartGroup from '../../components/smart/ChartGroup';

// import PracticeLineAreaChart from '../../components/dump/charts/PracticeLineAreaChart';
// import NewMissionLineAreaChart from '../../components/dump/charts/NewMissionLineAreaChart';
// import MissionLineAreaChart from '../../components/dump/charts/MissionLineAreaChart';
// import PKLineAreaChart from '../../components/dump/charts/PKLineAreaChart';
import StudentRetainedTableChart from '../../components/dump/charts/StudentRetainedTableChart';

import omit from 'lodash/object/omit';

import { ENUM_VIEW, DATE_FORMATTER } from '../../../schema/constants';
import { setCondition } from '../../actions/fixup-work/conditionAction';
import moment from 'moment';

import * as ACTIONS from '../../actions/retained/studentMissionRetainedAction';

function mapStateToProps(state) {
	return {
		retained: state.retained,
		condition: state.chart.condition
	};
}

function getData(condition, userParams) {
    return ACTIONS.getRetainedData({
        condition: omit(condition, 'dataOptions'),
        ...userParams
    });
}

class StudentMissionRetained extends React.Component {

	constructor(props) {
		super(props);

		this._timeId = 0;
	}

	state = {
		currentTimeUnit: ENUM_VIEW.DAY,
		cycle: '7',
		type: ACTIONS.TypeOption.RATE,
		actionText: ''
	};

	// 输入周期长度
	handleCycleInput = (event) => {
        let { dispatch, condition } = this.props;
		let cycle = event.target.value;

		this.setState({
			cycle,
			actionText: '改变周期长度'
		});

        if (cycle.trim() == '' || isNaN(cycle.trim()))
            return console.log('周期长度只能输入数字');
        if (+cycle > 90)
            return console.log('不能查看90天以外的数据');

		clearTimeout(this._timeId);
		this._timeId = setTimeout(() => {
			// get data
            dispatch(getData(condition, this.state));
		}, 500)
	};

    // 切换时间颗粒度
    handleTimeUnitChange = (option) => {
        let { dispatch, condition } = this.props;

        this.setState({
            currentTimeUnit: option,
            actionText: '改变事件颗粒度'
        }, () => {
            // get data
            dispatch(getData(condition, this.state));
        });
    };

    // 处理日期范围变化
    handleDateRangeChange = (startDate, endDate) => {
        let { dispatch } = this.props;

        let action = setCondition('startDate', moment(startDate).format(DATE_FORMATTER));
        dispatch(action);

        action = setCondition('endDate', moment(endDate).format(DATE_FORMATTER));
        dispatch(action);

        this.setState({
        	actionText: '改变日期范围'
        });

        setTimeout(() => {
            // get data
            let { condition } = this.props;
            dispatch(getData(condition, this.state));
        }, 0);
    };

    // 点击高级筛选条件查询按钮
    handleSearch = () => {
        let { dispatch, condition } = this.props;

        // get data
        dispatch(getData(condition, this.state));
    };

    // 数据类型变化
    handleTypeChange = (type) => {
    	this.setState({
    		type,
    		actionText: '数据类型变化'
    	})
    };

    componentWillMount() {
        let { dispatch, condition } = this.props;
        // get data
        dispatch(getData(condition, this.state));
    }

	render() {
		let { retained, condition } = this.props;
        let { startDate, endDate } = condition;
        let { currentTimeUnit,
            type, cycle, actionText } = this.state;

        let { retainedCountData, retainedRateData, summary } = retained;

        let hintText = '';
        if (currentTimeUnit == ENUM_VIEW.DAY)
        	hintText = '天';
        else if (currentTimeUnit == ENUM_VIEW.WEEK)
        	hintText = '周';
        else if (currentTimeUnit == ENUM_VIEW.MONTH)
        	hintText = '月';

		return (
			<div className='panel'>
                <StudentFilter onSearch={this.handleSearch} />
                <ChartGroup
                    onDateRangeChange={this.handleDateRangeChange}
                    startDate={startDate}
                    endDate={endDate}>
                    <Tabs
                        onChange={this.handleTimeUnitChange}
                        value={currentTimeUnit}>
                        <Tab label='日' value={ENUM_VIEW.DAY}></Tab>
                        <Tab label='周' value={ENUM_VIEW.WEEK}></Tab>
                        <Tab label='月' value={ENUM_VIEW.MONTH}></Tab>
                    </Tabs>
                    <div style={{textAlign: 'center', padding: 10 }}>
                        <FlatButton label='留存率' secondary={type == ACTIONS.TypeOption.RATE}
                            onClick={() => this.handleTypeChange(ACTIONS.TypeOption.RATE)} />
						<FlatButton label='留存数' secondary={type == ACTIONS.TypeOption.COUNT}
							onClick={() => this.handleTypeChange(ACTIONS.TypeOption.COUNT)} />
						<TextField
							style={{width: 100, marginLeft: 10}}
							onInput={this.handleCycleInput}
							value={cycle}
					      	hintText={hintText}
					      	floatingLabelText={`周期长度`}
					      	floatingLabelFixed={true}
					    />
					</div>
                    <div className='chart'>
                    {type == ACTIONS.TypeOption.COUNT &&
                        <StudentRetainedTableChart dataSource={summary} type={ACTIONS.TypeOption.COUNT} cycle={cycle} cycleUnit={hintText} />
                    }
                    {type == ACTIONS.TypeOption.RATE &&
                        <StudentRetainedTableChart dataSource={summary} type={ACTIONS.TypeOption.RATE} cycle={cycle} cycleUnit={hintText} />
                    }
                	</div>
                </ChartGroup>
            </div>
		);
	}
}

export default connect(
	mapStateToProps,
	// Implement map dispatch to props
)(StudentMissionRetained)

